import React, {useMemo, useCallback, useState} from 'react';
import {Card, Table, Button, Spin} from 'antd';
import {download} from '~/service/refundReport';
import {addDashBoardIdToDimensionAndValues} from '../../common/utils';

const OrderOfflineTableCard = props => {
    const {
        dashBoard: {dashBoardId} = {},
        unitId,
        dimensionAndValues = [],
        pageInfo,
        tableData,
        loading,
        onTableChange
    } = props;

    const {data, pager} = tableData || {};
    const [isDownLoading, setIsDownLoading] = useState(false);
    // 获取表格列和数据
    const {columns, dataSource, unitName, count} = useMemo(() => {
        const unit = dashBoardId ? data?.[dashBoardId]?.[unitId] : {};
        const {columnList = [], value = [], unitName = ''} = unit || {};
        const sorter = name => (a, b) => (a?.[name] === b?.[name] ? 0 : a?.[name] > b?.[name] ? 1 : -1);
        const columns =
            columnList?.map(({id, name}) => ({
                id,
                name,
                key: id,
                title: name,
                dataIndex: name,
                sorter: sorter(name),
                sortDirections: ['descend', 'ascend'],
            })) ?? [];
        const dataSource =
            value?.map((item = {}, index) => ({
                ...item,
                key: index
            })) ?? [];
        const count = pager?.count ?? 0;
        return {columns, dataSource, unitName, count};
    }, [data, pager]);

    // 获取分页信息
    const pagination = {
        current: pageInfo.pageNum,
        pageSize: pageInfo.pageSize,
        total: count,
        hideOnSinglePage: true
    };

    // 下载
    const handleDownload = useCallback(() => {
        const params = {
            dimensionAndValues: addDashBoardIdToDimensionAndValues(
                dimensionAndValues,
                dashBoardId
            ),
            unitId,
            unitName
        };
        const excelName = unitName ? unitName : null;
        // 设置导出下载
        setIsDownLoading(true);
        download(params, excelName, () => setIsDownLoading(false));
    }, [dimensionAndValues, dashBoardId, unitId, unitName]);

    return (
        <Card
            title={unitName || '订单离线数据表'}
            extra={(
                <Button
                    onClick={handleDownload}
                    loading={isDownLoading}
                    disabled={!dataSource?.length}
                >
                    明细导出
                </Button>
            )}
            className="order-offline-table-card"
        >
            <Spin spinning={loading}>
                <Table
                    columns={columns}
                    dataSource={dataSource}
                    scroll={{x: 'max-content'}}
                    onChange={onTableChange}
                    pagination={pagination}
                />
            </Spin>
        </Card>
    );
};

export default OrderOfflineTableCard;
